<template>
  <div class="category">
    <h1>{{ id ? "编辑" : "新建" }}分类</h1>
    <el-form label-width="120px" v-model="form" @submit.native.prevent="save">
      <el-form-item label="上级分类">
        <el-select v-model="form.parent">
          <el-option
            v-for="item in parentOptions"
            :key="item._id"
            :value="item._id"
            :label="item.name"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="名称">
        <el-input v-model="form.name"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" native-type="submit">保存</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
/* eslint-disable */
export default {
  name: "CatagoryEdit",
  props: {
    id: {},
  },
  data() {
    return {
      form: {
        name: "",
      },
      parentOptions: [], // 父级选项
    };
  },
  created() {
    this.id && this.edit(); // 判断是否有id,有则执行后面的方法
    this.getParentOptions();
  },
  mounted() {},
  methods: {
    // 获得分类列表
    save() {
      let res;
      if (this.id) {
        // 如果存在id，则调用编辑的接口
        res = this.$http.put(`rest/categories/${this.id}`, this.form); // 调用这个接口
      } else {
        res = this.$http.post("rest/categories", this.form); // 调用这个接口
      }
      this.$router.push("/categories/list"); // 路由跳转
      this.$message({
        type: "success",
        message: "保存成功！！！",
      });
    },
    // 获得详情
    async edit() {
      const res = await this.$http.get(`rest/categories/${this.id}`); // 调用接口
      this.form = res.data; // 将查询到的数据返回到页面
    },
    // 获得详情
    async getParentOptions() {
      const res = await this.$http.get(`rest/categories`); // 调用接口
      this.parentOptions = res.data; // 将查询到的数据返回到页面
    },
  },
};
</script>

<style scoped></style>
